package com.itita.ww2.handler.requesthandler.item;

import java.sql.SQLException;

import com.itita.ww2.core.MessageHandler;
import com.itita.ww2.core.WW2Exception;
import com.itita.ww2.game.item.ItemService;
import com.itita.ww2.game.user.UserInventoryManager;
import com.itita.ww2.game.user.UserService;
import com.itita.ww2.model.user.UserProfile;
import com.itita.ww2.utils.handler.IRequestOper;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;

/**
 * 合成并装备
 * @author NorthLan
 *
 */
public class CompositeEquipment implements IRequestOper {

	@Override
	public boolean execute(String requestCMD, User user, ISFSObject params) throws WW2Exception, SQLException {
		UserProfile userProfile = UserService.getInstance().getUserProfile(user);
		String itemId = params.getUtfString("itemId");
		String armyId = params.getUtfString("armyId");
		String grid = params.getUtfString("grid");

		UserInventoryManager inventory = userProfile.getInventory();
		inventory.backup();
		try {
			ItemService.compositeAndEquip(userProfile, itemId, armyId, grid);
		} catch (Exception e) {
			inventory.rollback();
			throw e;
		} finally {
			inventory.clean();
		}

		// 新手引导设置一下
		if (params.containsKey("guidestep")) {
			userProfile.getUserInfo().setGuideStep(params.getInt("guidestep"));
		}

		inventory.update();

		ISFSObject backObj = SFSObject.newInstance();
		backObj.putSFSArray("inventory", inventory.toSFSArray());
		MessageHandler.getInstance().sendMsg(requestCMD, backObj, user, null, true);
		return true;
	}

}
